package com.shu.Thread;

import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author ssm
 * @version V1.0
 * @description:
 * @date 2019/4/9 12:55
 */

/**
 * 线程池5中状态:
 * running:线程池能接受新的任务
 * shutdown:线程池不接受新任务,但是执行队列的任务会执行完毕
 * stop:不接受新任务,执行队列任务会被立即终止(ps:调用线程池的shutDownNow实现)
 * tidying:所有任务已被终止
 * terminated:现场清理完毕
 */
public class ThreadPoolState {

    /**
     * shutdown 和 shutdownNow的 区别
     *
     * @throws InterruptedException
     */
    @Test
    @DisplayName("shutdown 和 shutdownNow的 区别")
    public void test1() throws InterruptedException {
        CountDownLatch CountDownLatch = new CountDownLatch(1000);
        AtomicInteger success = new AtomicInteger(0);
        Runnable runable = () -> {
            try {
                TimeUnit.MILLISECONDS.sleep(100);
                System.out.println(success.incrementAndGet() + "----执行完毕");
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                CountDownLatch.countDown();
            }
        };

        ExecutorService cachedThreadPool = Executors.newCachedThreadPool();
        for (int i = 0; i < 1000; i++) {
            cachedThreadPool.submit(runable);
        }
        cachedThreadPool.shutdown(); // 标记状态为停止,不接受新的线程,但是会把执行队列执行完毕
        System.out.println("----" + cachedThreadPool.isShutdown());
//        cachedThreadPool.shutdownNow(); // 立即停止,执行队列正在执行的线程会调用强行终止

        CountDownLatch.await();
        System.out.println("执行完毕!");
        System.out.println("----" + cachedThreadPool.isShutdown());

    }
}
